import {
  Get,
  Post,
  JsonPost
} from "./utils/request.js"
//app.js
App({
  onLaunch: function (options) {
    console.log(options);
    var that = this
    if (options.query.scene) {
      this.globalData.shareUid= decodeURIComponent(options.query.scene).split("?goods_id=")[1].split("?uid=")[1]
    }
    // 判断是否为苹果X
    wx.getSystemInfo({
      success(res) {
        // console.log(res, "getSystemInfoSync")
        var a = res.model;
        if (-1 != a.search("iPhone X") || -1 != a.search("iPhone XS")) {
          that.globalData.wpxIos = true
        }
      }
    })

    if (wx.getStorageSync('token') && (new Date().getTime() - wx.getStorageSync('loginTime') < 604800000)) {
      this.globalData.login=true
    } else {
      this.ttClogin()
    }
  },
  ttClogin() {
    wx.getSetting({
      success: res => {

        if (res.authSetting['scope.userInfo']) {
          wx.login({
            success: loginRes => {
              // console.log(loginRes.code);
              // 发送 res.code 到后台换取 openId, sessionKey, unionId
              // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
              wx.getUserInfo({
                success: userInfo => {
                  // 可以将 res 发送给后台解码出 unionId
                  this.globalData.userInfo = userInfo.userInfo
                  wx.setStorageSync('userInfo', JSON.stringify(userInfo.userInfo))
                  JsonPost('user/login', {
                    'code': loginRes.code,
                    encryptedData: encodeURIComponent(userInfo.encryptedData),
                    iv: userInfo.iv
                  }).then(endRes => {
                    this.globalData.login=true
                    wx.setStorageSync('token', endRes.data.token)
                    wx.setStorageSync('loginTime', new Date().getTime())
                  })
                  // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                  // 所以此处加入 callback 以防止这种情况
                  if (this.userInfoReadyCallback) {
                    this.userInfoReadyCallback(res)
                  }
                }
              })
            }
          })
        }
      }
    })
  },
   
  
  globalData: {
    userInfo: null,
    wpxIos: false,
    open: false,
    adressInfo:null,
    login:false,
    // 选中门店信息
    storeInfo:null,
    invoice_id:null,
    shopCartInfo:[],
    couponInfo:{},
    // 分享人uid
    shareUid:null,
  }
})